/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: AssetUtilsManager.java
 *   @Date: 2/1/19 3:18 PM
 *   @Author: chenjun
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.sdk.data_manager;

import android.os.Handler;
import android.os.Message;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.trade.AssetApi;
import io.bhex.sdk.trade.OptionApi;
import io.bhex.sdk.trade.bean.AllAssetResponse;
import io.bhex.sdk.trade.bean.IndicesResponse;
import io.bhex.sdk.trade.bean.OptionIndicesResponse;
import io.bhex.sdk.trade.futures.FuturesApi;

public class AssetUtilsManager {

    AllAssetResponse mAllAssetResponse;
    private List<AssetChangeInterface> assetObservers = new ArrayList<>();
    private List<IndexChangeInterface> indexObservers = new ArrayList<>();

    private Timer timer;
    private TimerTask task;
    private static final int nPeriod = 5 * 1000;
    private Handler mHandler;
    private final int ASSET_CHANGE = 0X1;
    private Map<String, String> mIndexMapsOfOption = new HashMap<>();
    private Map<String, String> mIndexMapsOfFutures = new HashMap<>();

    private static AssetUtilsManager mInstance;

    private boolean isRequestingAsset=false;

    public static AssetUtilsManager GetInstance() {
        if (mInstance == null) {

            mInstance = new AssetUtilsManager();
        }

        return mInstance;
    }

    public interface AssetChangeInterface {
        void OnAssetChanged();
    }

    public interface IndexChangeInterface {
        void OnIndexChanged();
    }

    public void AddAssetObserver(AssetChangeInterface assetObserver) {
        assetObservers.add(assetObserver);
        mHandler.sendEmptyMessage(ASSET_CHANGE);
    }

    public void removeAssetObserver(AssetChangeInterface assetObserver) {
        assetObservers.remove(assetObserver);
    }

    public void AddIndexObserver(IndexChangeInterface assetObserver) {
        indexObservers.add(assetObserver);
        mHandler.sendEmptyMessage(ASSET_CHANGE);
    }

    public void removeIndexObserver(IndexChangeInterface assetObserver) {
        indexObservers.remove(assetObserver);
    }

    AssetUtilsManager() {


        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case ASSET_CHANGE:
                        requestAllAsset();
                        requestAllIndexesOfOption();
                        requestAllIndexesOfFutures();
                        break;
                }
            }
        };
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(ASSET_CHANGE);

            }
        };
        timer.schedule(task, 50, nPeriod);
    }

    public void release() {
        if (task != null) {
            task.cancel();
        }
        if (timer != null) {
            timer.purge();
            timer.cancel();
        }
        mInstance = null;
    }



    public synchronized void requestAllAsset() {
        if(UserInfo.isLogin() && assetObservers.size() > 0 && !isRequestingAsset) {

            AssetApi.RequstAllAsset(new SimpleResponseListener<AllAssetResponse>() {
                @Override
                public void onBefore() {
                    super.onBefore();
                    isRequestingAsset = true;
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    isRequestingAsset = false;
                }

                @Override
                public void onSuccess(AllAssetResponse response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response)) {
                        mAllAssetResponse = response;
                        for (AssetChangeInterface observer : assetObservers) {
                            if (observer != null)
                                observer.OnAssetChanged();
                        }
                    }
                }

                @Override
                public void onError(Throwable error) {
                    super.onError(error);
                }
            });
        }

    }

    /**
     * 请求期权的所有index_token指数
     */
    private void requestAllIndexesOfOption() {
        OptionApi.RequestOptionIndices(SymbolDataManager.GetInstance().getAllIndexTokensOfOptions(), new SimpleResponseListener<OptionIndicesResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OptionIndicesResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    if (response.data != null) {
                        mIndexMapsOfOption.putAll(response.data);
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
        //}
    }

    /**
     * 获取期权指数
     *
     * @param index
     * @return
     */
    public String getSymbolIndexOfOption(String index) {
        return mIndexMapsOfOption.get(index);
    }

    /**
     * 请求期货的所有index_token指数
     */
    private void requestAllIndexesOfFutures() {
        FuturesApi.RequestIndices(SymbolDataManager.GetInstance().getAllIndexTokensOfFutures(), new SimpleResponseListener<IndicesResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(IndicesResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    if (response.data != null) {
                        mIndexMapsOfFutures.putAll(response.data);
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
        //}
    }

    /**
     * 获取期货指数
     *
     * @param index
     * @return
     */
    public String getSymbolIndexOfFutures(String index) {
        return mIndexMapsOfFutures.get(index);
    }

    public AllAssetResponse GetAllAsset() {
        return mAllAssetResponse;
    }


}
